const moneyGoalService = require('../services/moneyGoalService');
let R = require('../result/r');

/**
 * moneyGoalController
 * Controller 是业务入口，由 HTTP 路由解析后调用
 * 包含攒钱计划的增删改查功能
 */
class moneyGoalController {
    /**
     * 列出所有攒钱计划
     */
    async listAll(ctx) {
        const list = await moneyGoalService.listAll();
        ctx.body = R.ok().data(list);
    }

    /**
     * 查询分页
     */
    async queryPage(ctx) {
        const params = ctx.request.body;
        const list = await moneyGoalService.queryPage(params);
        for (const one of list) {
            one.curMoneyTotal = await moneyGoalService.countCurMoney(one._id+"")
        }
        ctx.body = R.ok().data(list);
    }

    /**
     * 查询一条数据根据id
     */
    async getOneById(ctx) {
        const one = await moneyGoalService.getOneById(ctx.params.id);
        ctx.body = R.ok().data(one);
    }

    /**
     * 创建一条攒钱计划
     */
    async add(ctx) {
        const moneyGoal = ctx.request.body;
        const result = await moneyGoalService.create(moneyGoal);
        ctx.body = R.ok("新增成功").data(result);
    }

    /**
     * 删除一条攒钱计划
     * @param ctx Koa 的上下文参数
     */
    async deleteById(ctx) {
        //console.log(ctx.params.id)
        await moneyGoalService.delete(ctx.params.id);
        ctx.body = R.ok("删除成功");
    }


    /**
     * 更新攒钱计划
     */
    async updateOneById(ctx) {
        const moneyGoal = ctx.request.body;
        await moneyGoalService.update(moneyGoal);
        ctx.body = R.ok("更新成功");
    }


}

// 导出 Controller 的实例
module.exports = new moneyGoalController();
